package com.zbkj.service.service.mszs;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.model.mszs.MszsHotel;
import com.zbkj.common.model.mszs.MszsRoom;
import com.zbkj.common.model.mszs.MszsRoomType;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.request.mszs.MszsHotelRequest;
import com.zbkj.common.request.mszs.MszsHotelSelectRequest;
import com.zbkj.common.request.mszs.MszsIndexRequest;
import com.zbkj.common.response.mszs.MszsHotelResponse;
import com.zbkj.common.response.mszs.MszsRoomOrderResponse;
import com.zbkj.common.response.mszs.MszsRoomResponse;
import com.zbkj.common.token.FrontTokenComponent;
import com.zbkj.service.dao.user.UserDao;
import com.zbkj.service.dao.mszs.MszsHotelDao;
import com.zbkj.service.dao.mszs.MszsRoomDao;
import com.zbkj.service.service.publics.attachment.SystemAttachmentService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description 民宿助手酒店信息
 * @author zhengkai.blog.csdn.net
 * @date 2023-11-16
 */
@Service
public class MszsHotelServiceImpl extends ServiceImpl<MszsHotelDao, MszsHotel> implements MszsHotelService {

    @Resource
    private MszsHotelDao hotelDao;
    @Resource
    private MszsRoomDao roomDao;

    @Autowired
    private MszsRoomService mszsRoomService;

    @Autowired
    private MszsRoomTypeService roomTypeService;

    @Resource
    private MszsOrderService orderService;
    @Resource
    private UserDao userDao;
    @Autowired
    private FrontTokenComponent tokenComponent;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Override
    public boolean insert(MszsHotelRequest request) {
        MszsHotel hotel=new MszsHotel();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            if (StringUtils.isNotEmpty(request.getCallTimeEnd()) && StringUtils.isNotEmpty(request.getCallTimeStart())) {
                Date callTimeEnd = format.parse(request.getCallTimeEnd());
                Date callTimeStart = format.parse(request.getCallTimeStart());

                hotel.setCallTimeEnd(callTimeEnd);
                hotel.setCallTimeStart(callTimeStart);
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        BeanUtils.copyProperties(request, hotel);
        if (request.getJdImg()!=null && request.getJdImg().size()>0) {
            String img = StringUtils.join(request.getJdImg(),",");
            hotel.setJdImg(systemAttachmentService.clearPrefix(img));
        }
        int mh = hotelDao.insert(hotel);
        return mh > 0;
    }

    @Override
    public boolean update(MszsHotelRequest request) {

        MszsHotel hotel=new MszsHotel();
        BeanUtils.copyProperties(request, hotel);
        if (request.getJdImg()!=null && request.getJdImg().size()>0) {
            String img = StringUtils.join(request.getJdImg(),",");
            hotel.setJdImg(systemAttachmentService.clearPrefix(img));
        }
        int mh = hotelDao.updateById(hotel);

        return mh > 0;
    }

    @Override
    public boolean delete(String id) {
        int mh = hotelDao.deleteById(id);
        return mh > 0;
    }

    @Override
    public List<MszsHotelResponse> getUserHotelList(Integer uid) {

        LambdaQueryWrapper<MszsHotel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(MszsHotel::getUid,uid);

        lambdaQueryWrapper.orderByDesc(MszsHotel::getSort).orderByDesc(MszsHotel::getCreateTime);

        List<MszsHotel> hotelList = hotelDao.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(hotelList)) {
            return CollUtil.newArrayList();
        }
        List<MszsHotelResponse> responseList = hotelList.stream().map(e -> {
            MszsHotelResponse hotelResponse = new MszsHotelResponse();
            BeanUtils.copyProperties(e, hotelResponse);
            return hotelResponse;
        }).collect(Collectors.toList());
        return responseList;
    }

    @Override
    public MszsHotelResponse load(String id) {

        MszsHotel hotel = hotelDao.selectById(id);
        MszsHotelResponse hotelResponse=new MszsHotelResponse();
        BeanUtils.copyProperties(hotel,hotelResponse);
        if (StringUtils.isNotEmpty(hotel.getJdImg())){
            //string转list
            List<String> iamge = Arrays.asList(hotel.getJdImg().split(","));
            hotelResponse.setJdImg(iamge);
        }else {
            List<String > list = new ArrayList<>();
            hotelResponse.setJdImg(list);
        }
        User user = userDao.selectById(hotel.getUid());
        if (Objects.nonNull(user)){
            hotelResponse.setNickname(user.getNickname());
            hotelResponse.setRealName(user.getRealName());
        }
        return hotelResponse;
    }

    @Override
    public List<MszsHotel> adminPageList(MszsHotelSelectRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        LambdaQueryWrapper<MszsHotel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(request.getJdName())){
            lambdaQueryWrapper.like(MszsHotel::getJdName,request.getJdName());
        }
        if (StringUtils.isNotEmpty(request.getJdAddress())){
            lambdaQueryWrapper.like(MszsHotel::getJdAddress,request.getJdAddress());
        }
        lambdaQueryWrapper.orderByDesc(MszsHotel::getSort).orderByDesc(MszsHotel::getCreateTime);

        List<MszsHotel> hotelList = hotelDao.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(hotelList)) {
            return CollUtil.newArrayList();
        }

        return hotelList;
    }

    @Override
    public List<MszsHotel> pageList(MszsHotelSelectRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        Integer uid = tokenComponent.getUserId();
        LambdaQueryWrapper<MszsHotel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(MszsHotel::getUid,uid);
        if (StringUtils.isNotEmpty(request.getJdName())){
            lambdaQueryWrapper.like(MszsHotel::getJdName,request.getJdName());
        }
        if (StringUtils.isNotEmpty(request.getJdAddress())){
            lambdaQueryWrapper.like(MszsHotel::getJdAddress,request.getJdAddress());
        }
        lambdaQueryWrapper.orderByDesc(MszsHotel::getSort).orderByDesc(MszsHotel::getCreateTime);

        List<MszsHotel> hotelList = hotelDao.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(hotelList)) {
            return CollUtil.newArrayList();
        }

        return hotelList;
    }

    /**
     * 房间信息-根据字段排序
     * @param roomQueryWrapper  查询对象
     * @param field             排序字段
     * @param sortParamValue    排序参数值:升序或降序：0=升序
     */
    private void sortByField(QueryWrapper<MszsRoom> roomQueryWrapper, String field, Integer sortParamValue) {
        if (sortParamValue == 0) {
            roomQueryWrapper.orderByAsc(field);
        } else {
            roomQueryWrapper.orderByDesc(field);
        }
    }

    /**
     * 获取酒店数据（重构版）
     * -包括每个酒店的房间数据
     * -房间数据（分页）
     * -获取了房型数据
     * -房间根据入住状态获取了订单
     * @param request           请求参数
     * @param paramRequest      分页参数
     * @return List<MszsHotelResponse>
     */
    @Override
    public List<MszsHotelResponse> hotelListReconfiguration(
            MszsIndexRequest request, PageParamRequest paramRequest) {
        //定义查询-查询该用户下酒店数据列表
        LambdaQueryWrapper<MszsHotel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MszsHotel::getUid,tokenComponent.getUserIdCrmebException());
        //得到数据-酒店列表
        List<MszsHotel> hotelList = hotelDao.selectList(lambdaQueryWrapper);

        //返回数据
        return hotelList.stream().map(hotel -> {
            //转换-酒店数据响应对象
            MszsHotelResponse hotelResponse = new MszsHotelResponse();
            BeanUtils.copyProperties(hotel, hotelResponse);

            //查询房间信息
            QueryWrapper<MszsRoom> roomQueryWrapper = new QueryWrapper<>();
            //条件-酒店id
            roomQueryWrapper.eq("jd_id",hotel.getId());
            //条件-房间名称-排序
            Optional.ofNullable(request.getRoomTypeSort()).ifPresent(roomName ->{
                roomQueryWrapper.orderBy(true,(roomName == 0),"fj_name");
            });
            //条件-房间状态-排序
            Optional.ofNullable(request.getStatusSort()).ifPresent(status ->{
                roomQueryWrapper.orderBy(true,(status == 0),"status");
            });
            //条件-房间价格-排序
            Optional.ofNullable(request.getPriceSort()).ifPresent(price ->{
                sortByField(roomQueryWrapper, "fj_price", price);
            });

            //开启分页，第一个参数为当前页码，第二个参数为每页数量
            PageHelper.startPage(paramRequest.getPage(), paramRequest.getLimit());
            //获取查询结果
            List<MszsRoom> roomList = mszsRoomService.list(roomQueryWrapper);
            List<MszsRoomResponse> roomResponsesList = roomList.stream().map(room -> {
                //转换-房间数据响应对象
                MszsRoomResponse roomResponse = new MszsRoomResponse();
                BeanUtils.copyProperties(room, roomResponse);

                //得到-房型数据
                MszsRoomType roomType = roomTypeService.getById(room.getFxId());
                roomResponse.setFxName(Optional.ofNullable(roomType).map(MszsRoomType::getFxName).orElse("【没有设置房型】"));

                //检查房间是否已入住
                Optional<Integer> status = Optional.ofNullable(roomResponse.getStatus());
                if (status.isPresent() && status.get() == 1) {
                    MszsRoomOrderResponse order = orderService.roomCheckIn(roomResponse.getId());
                    Optional.ofNullable(order).ifPresent(o->{
                        roomResponse.setRuzhuren(o.getRuzhuren());
                        roomResponse.setOrderId(o.getId());
                    });
                }

                //房间数据响应对象
                return roomResponse;
            }).collect(Collectors.toList());

            //将房间list添加到酒店list
            hotelResponse.setRoomList(roomResponsesList);
            return hotelResponse;
        }).collect(Collectors.toList());
    }

}
